import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { UserInfo } from '@/api/interfaceDto/UserInfo'
import { getCurrentUser } from '@/api/auth'
import { queryStationConfig } from '@/api/h3yun'
import { ErrorCode } from '@/constants/errorCode'


export const useUserStore = defineStore('user', () => {

  const userInfo = ref<UserInfo | null>(null) // 存储用户信息
  const isFetched = ref<boolean>(false) // 标记是否已获取用户信息
  const stationConfig = ref<any | null>(null) // 存储单站配置
  const selectedAreaCode = ref<string>('') // 存储区域编码

  // 获取用户信息的方法
  const fetchUserInfo = async (): Promise<void> => {
    try {
      const response = await getCurrentUser()
      if (response.code === ErrorCode.SUCCESS) {
        userInfo.value = response.data // 存储用户信息
        isFetched.value = true // 标记为已获取
        setSelectedAreaCode(userInfo.value?.powerCode === 'admin' ? '' : userInfo.value?.unitId)
      } else {
        throw new Error(response.msg)
      }
    } catch (error) {
      userInfo.value = null
      isFetched.value = false
      throw error
    }
  }

  const fetchStationConfig = async (): Promise<void> => {
    const response = await queryStationConfig({areaCode: selectedAreaCode.value})
    if (response.code === ErrorCode.SUCCESS) {
      stationConfig.value = response.data
    }
    return stationConfig.value
  }

  const setSelectedAreaCode = (areaCode: string) => {
    selectedAreaCode.value = areaCode
  }

  return {
    userInfo,
    isFetched,
    fetchUserInfo,
    fetchStationConfig,
    stationConfig,
    selectedAreaCode,
    setSelectedAreaCode,
  }
})


